import * as step from '@flow-step/step-toolkit'

const FLOW_JOB_TOKEN: string = 'FLOW_JOB_TOKEN'

export async function getKubernetesCertificate() {
    const kubernetesConnectionId = process.env['KUBERNETES_CONNECTION_ID']
    if (kubernetesConnectionId == undefined) {
        throw new Error('missing KUBERNETES_CONNECTION_ID')
    }

    const flowJobToken: string | undefined =
        process.env[FLOW_JOB_TOKEN]

    if (flowJobToken == undefined) {
        throw new Error('missing FLOW_JOB_TOKEN')
    }

    const kubernetesCertificate = await step.certificate.getKubernetesCertificate(flowJobToken, kubernetesConnectionId as string)
    if (kubernetesCertificate === undefined || kubernetesCertificate.type === '') {
        throw new Error(`get KubernetesCertificate but error: ${JSON.stringify(kubernetesCertificate)}`)
    }

    step.debug(`get KubernetesCertificate data: ${JSON.stringify(kubernetesCertificate)}`)
    return Promise.resolve(kubernetesCertificate)
}